package com.lwj.liwanjia.view.activity.login;

import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.Text;
import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.DbAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.DbBean;
import com.lwj.liwanjia.bean.RegisterBean;
import com.lwj.liwanjia.bean.XiuGaiMiMaYZM;
import com.lwj.liwanjia.config.URLConstant;
import com.lwj.liwanjia.utils.Code;
import com.lwj.liwanjia.utils.TimeCount;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 001 on 2017/9/5.
 */

public class  RegisterActivity extends BaseActivity implements View.OnClickListener {

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    Toast.makeText(RegisterActivity.this, "注册的验证码接口有问题", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(RegisterActivity.this, "验证码获取失败", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(RegisterActivity.this, "验证码获取成功", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(RegisterActivity.this, "注册账号的接口有问题", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 6:
                    Toast.makeText(RegisterActivity.this, "非法账号", Toast.LENGTH_SHORT).show();
                    break;
                case 7:
                    Toast.makeText(RegisterActivity.this, "非法密码", Toast.LENGTH_SHORT).show();
                    break;
                case 8:
                    Toast.makeText(RegisterActivity.this, "账号已存在", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private TextView tv_title;//头布局标题
    private TextView tv_back;//头布局左边的返回按钮
    private List<DbBean> provinceList = new ArrayList();//省的数据集合
    private List<DbBean> cityList = new ArrayList<>();//市的数据集合
    private List<DbBean> districtList = new ArrayList();//区的数据集合
    private PopupWindow popupWindow;//展示省市区的控件
    private ListView provinceListView;//省的数据集合
    private LinearLayout ll_province;//省份容器
    private File dbFile;//存储省市区数据的文件
    private DbAdapter mAdapter;
    private LinearLayout ll_city;//市的容器
    private ListView cityListView;//市的数据集合
    private ListView districtListView;//区的数据集全
    private LinearLayout ll_district;//区的容器

    private TextView tv_province;//省
    private TextView tv_city;//市
    private TextView tv_district;//区
    private EditText et_address;//街道
    private EditText et_yaoQing;//邀请码
    private EditText et_number;//手机号码
    private EditText et_yanZhengMa;//验证码
    private EditText et_password;//密码
    private Button bt_register;//注册
    private TextView tv_yanZhengMa;//验证码(点击)

    private String province;
    private String city;
    private String district;
    private String address;
    private String yaoQing;
    private String phoneNumber;
    private String yanZhengMa;
    private String password;
    private CountDownTimer timer;
    private ImageView ivYicang;
    private int click = 0;//密码是否隐藏，0代表是
    private ImageView ivTxm;
    private EditText edTxm;

    private boolean isCheck01;
    private boolean isCheck02;
    private boolean isCheck03;
    private String code;
    private String code1;

    @Override
    protected void initView() {

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_back = (TextView) findViewById(R.id.tv_left);
        et_address = (EditText) findViewById(R.id.et_address);
        tv_province = (TextView) findViewById(R.id.tv_province);
        ll_province = (LinearLayout) findViewById(R.id.ll_province);
        ll_city = (LinearLayout) findViewById(R.id.ll_city);
        tv_city = (TextView) findViewById(R.id.tv_city);
        ll_district = (LinearLayout) findViewById(R.id.ll_district);
        tv_district = (TextView) findViewById(R.id.tv_district);
        et_yaoQing = (EditText) findViewById(R.id.et_yaoQing);
        et_number = (EditText) findViewById(R.id.et_number);
        et_yanZhengMa = (EditText) findViewById(R.id.et_yanZhengMa);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_register = (Button) findViewById(R.id.bt_register);
        tv_yanZhengMa = (TextView) findViewById(R.id.tv_yanZhengMa);
        ivYicang = (ImageView) findViewById(R.id.iv_yincang);
        ivTxm = (ImageView) findViewById(R.id.iv_txm);
        edTxm = (EditText) findViewById(R.id.edit_txm);

        tv_back.setOnClickListener(this);
        ll_province.setOnClickListener(this);
        ll_city.setOnClickListener(this);
        ll_district.setOnClickListener(this);
        bt_register.setOnClickListener(this);
        tv_yanZhengMa.setOnClickListener(this);
        ivYicang.setOnClickListener(this);
        ivTxm.setOnClickListener(this);

        //初始化UI
        tv_back.setText("返回");
        tv_back.setVisibility(View.VISIBLE);
        tv_title.setText("注册");
        et_address.setSelection(et_address.getText().length());
        ivTxm.setImageBitmap(Code.getInstance().createBitmap());
        code = Code.getInstance().getCode();
        code1 = code.toLowerCase();
        code1 = code.toLowerCase();
    }

    @Override
    protected void initData() {

        //读取数据库到文件中
        initDbToFile();

        //初始化PopupWindow
        initPopuoWindow();

        //省份的条目点击事件
        initProvinceListener();

        //市的条目点击事件
        initCityListener();

        //区的条目点击事件
        initDistrictListener();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回键
            case R.id.tv_left:
                finish();
                break;
            case R.id.iv_txm:
                ivTxm.setImageBitmap(Code.getInstance().createBitmap());
                code = Code.getInstance().getCode();
                code1 = code.toLowerCase();
                break;
            //省份的点击事件
            case R.id.ll_province:
                isCheck01 = true;
                //初始化省份数据并设置适配器
                initProvince();
                provinceListView.setVisibility(View.VISIBLE);
                cityListView.setVisibility(View.GONE);
                districtListView.setVisibility(View.GONE);
                //显示popupWindow
                popupWindow.showAsDropDown(ll_province);
                break;
            //市的点击事件
            case R.id.ll_city:
                isCheck02 = true;
                //先点击省,才能点击市
                if (cityList.size() > 0) {
                    provinceListView.setVisibility(View.GONE);
                    cityListView.setVisibility(View.VISIBLE);
                    districtListView.setVisibility(View.GONE);
                    popupWindow.showAsDropDown(ll_city);
                } else {
                    Toast.makeText(RegisterActivity.this, "请先选择省份", Toast.LENGTH_SHORT).show();
                }

                break;
            //区的点击事件
            case R.id.ll_district:
                isCheck03 = true;
                //情况一:先选择市,才能选择区
                if (districtList.size() > 0) {
                    provinceListView.setVisibility(View.GONE);
                    cityListView.setVisibility(View.GONE);
                    districtListView.setVisibility(View.VISIBLE);
                    popupWindow.showAsDropDown(ll_district);
                } else {
                    Toast.makeText(RegisterActivity.this, "请先选择市", Toast.LENGTH_SHORT).show();
                }

                break;
            //获取验证码
            case R.id.tv_yanZhengMa:
                String number = et_number.getText().toString().trim();
                String txm = edTxm.getText().toString().trim();
                if (TextUtils.isEmpty(txm)) {
                    Toast.makeText(this, "图形码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!code.equals(txm)&&!code1.equals(txm)) {
                    Toast.makeText(this, "图形码输入有误", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!number.matches("[1][34578]\\d{9}")) {
                    Toast.makeText(this, "手机号码格式不对", Toast.LENGTH_SHORT).show();
                    return;
                }
                //连接网络,获取验证码
                initYanZhengMa(number);
                timer = new CountDownTimer(60000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        tv_yanZhengMa.setClickable(false);
                        tv_yanZhengMa.setText("(" + millisUntilFinished / 1000 + ")秒");
                        tv_yanZhengMa.setTextColor(getResources().getColor(R.color.color454444));
                    }

                    @Override
                    public void onFinish() {
                        tv_yanZhengMa.setClickable(true);
                        tv_yanZhengMa.setText("重新发送");
                        tv_yanZhengMa.setTextColor(getResources().getColor(R.color.color454444));
                    }
                };
                timer.start();
                break;
            //注册按钮
            case R.id.bt_register:

                province = this.tv_province.getText().toString().trim();
                city = this.tv_city.getText().toString().trim();
                district = this.tv_district.getText().toString().trim();
                address = this.et_address.getText().toString().trim();
                yaoQing = this.et_yaoQing.getText().toString().trim();
                phoneNumber = this.et_number.getText().toString().trim();
                yanZhengMa = this.et_yanZhengMa.getText().toString().trim();
                password = this.et_password.getText().toString().trim();
                if (TextUtils.isEmpty(address)
                        || TextUtils.isEmpty(password)
                        || TextUtils.isEmpty(phoneNumber)
                        || TextUtils.isEmpty(yanZhengMa)
                        || !isCheck01
//                        || !isCheck02
                        || !isCheck03) {
                    Toast.makeText(this, "除了邀请码，其它数据不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!phoneNumber.matches("[1][34578]\\d{9}")) {
                    Toast.makeText(this, "手机号码格式不对", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!password.matches("^[A-Za-z0-9]{6,16}+$")) {
                    Toast.makeText(this, "密码只能是数字、字母以及长度是6-16位", Toast.LENGTH_SHORT).show();
                    return;
                }
                //请求网络 进行注册
                initRegister();
                break;
            case R.id.iv_yincang:
                if (click == 0) {
                    this.et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    click = 1;
                } else if (click == 1) {
                    this.et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    click = 0;
                }
                this.et_password.setSelection(this.et_password.getText().toString().length());
                break;

        }
    }


    //读取数据库到文件中
    private void initDbToFile() {

        dbFile = new File(getFilesDir(), "city.s3db");

        if (dbFile.exists()) {
            return;
        }

        Resources res = getResources();
        InputStream inputStream = res.openRawResource(R.raw.city);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(dbFile);
            byte[] byt = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(byt)) != -1) {
                fos.write(byt, 0, len);
            }
            inputStream.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化PopupWindow
    private void initPopuoWindow() {

        View popupView = View.inflate(RegisterActivity.this, R.layout.db_popupwindow, null);
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());

        provinceListView = (ListView) popupView.findViewById(R.id.lv_province);
        cityListView = (ListView) popupView.findViewById(R.id.lv_city);
        districtListView = (ListView) popupView.findViewById(R.id.lv_district);
    }

    //初始化省份数据并设置适配器
    private void initProvince() {

        provinceList.clear();

        //初始化数据
        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = database.rawQuery("select code,name from province", null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                byte[] blob = cursor.getBlob(1);
                String name = null;
                try {
                    name = new String(blob, "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                provinceList.add(dbBean);
            }
        }

        database.close();
        cursor.close();

        //设置适配器
        mAdapter = new DbAdapter(RegisterActivity.this, provinceList);
        provinceListView.setAdapter(mAdapter);


    }

    //获取市的数据并设置适配器
    private void initCity(DbBean bean) {

        //每获取新数据时,先清空之前数据
        cityList.clear();

        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        String sql = "select code,name from city where  pcode = ?";
        String[] selectionArry = new String[]{bean.code};
        Cursor cursor = database.rawQuery(sql, selectionArry);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                byte[] blob = cursor.getBlob(1);
                String name = null;
                try {
                    name = new String(blob, "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                cityList.add(dbBean);
            }
        }

        cursor.close();
        database.close();

        //设置适配器
        mAdapter = new DbAdapter(RegisterActivity.this, cityList);
        cityListView.setAdapter(mAdapter);

    }

    //获取区的数据并设置适配器
    private void initDistrict(DbBean bean) {

        districtList.clear();

        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        String sql = "select code,name from district where pcode = ?";
        String[] selectionArry = new String[]{bean.code};
        Cursor cursor = database.rawQuery(sql, selectionArry);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                String name = null;
                try {
                    name = new String(cursor.getBlob(1), "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                districtList.add(dbBean);
            }
        }

        cursor.close();
        database.close();

        //设置适配器
        mAdapter = new DbAdapter(RegisterActivity.this, districtList);
        districtListView.setAdapter(mAdapter);
    }

    //自动显示完市后,再获取该市的所有区,并设置适配器
    private void initAutoDistrict(DbBean cityBean) {

        districtList.clear();

        SQLiteDatabase database = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        String sql = "select code,name from district where pcode = ?";
        String[] selectionArry = new String[]{cityBean.code};
        Cursor cursor = database.rawQuery(sql, selectionArry);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                String name = null;
                try {
                    name = new String(cursor.getBlob(1), "gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DbBean dbBean = new DbBean();
                dbBean.code = code;
                dbBean.name = name;
                districtList.add(dbBean);
            }
        }

        cursor.close();
        database.close();

        //设置适配器
        mAdapter = new DbAdapter(RegisterActivity.this, districtList);
        districtListView.setAdapter(mAdapter);
    }

    //省份的条目点击事件
    private void initProvinceListener() {

        provinceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                DbBean bean = (DbBean) provinceListView.getItemAtPosition(position);

                //根据类型TextView显示省
                String province = bean.name;
                tv_province.setText(province);
                popupWindow.dismiss();

                //获取市的数据并设置适配器
                initCity(bean);

                //选完省后,市自动显示第一个内容
                DbBean cityBean = cityList.get(0);
                String city = cityBean.name;
                tv_city.setText(city);

                //自动显示完市后,再获取该市的所有区,并设置适配器
                initAutoDistrict(cityBean);

            }
        });
    }

    //市的条目点击事件
    private void initCityListener() {

        cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                DbBean bean = (DbBean) cityListView.getItemAtPosition(position);

                //根据类型TextView显示市
                String city = bean.name;
                tv_city.setText(city);
                popupWindow.dismiss();

                //获取区的数据并设置适配器
                initDistrict(bean);

                //选完市后,区自动显示第一个内容
                DbBean districtBean = districtList.get(1);
                String district = districtBean.name;
                tv_district.setText(district);
            }
        });
    }

    //区的条目点击事件
    private void initDistrictListener() {

        districtListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                DbBean bean = (DbBean) districtListView.getItemAtPosition(position);

                //根据类型TextView显示市
                String city = bean.name;
                tv_district.setText(city);
                popupWindow.dismiss();

            }
        });
    }

    //连接网络,获取验证码
    private void initYanZhengMa(String number) {
        String url = URLConstant.BASE_URL + "user/sendSMS.do";
        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("name", number)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = null;
                try {
                    result = response.body().string();
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(0);
                }
                parseYanZhengMa(result);
            }
        });
    }

    //解析验证码
    private void parseYanZhengMa(String result) {
        Gson gson = new Gson();
        XiuGaiMiMaYZM bean = gson.fromJson(result, XiuGaiMiMaYZM.class);
        if (bean != null) {
            switch (bean.getState()) {
                case 0:
                    mHandler.sendEmptyMessage(1);
                    break;
                case 1:
                    mHandler.sendEmptyMessage(2);
                    break;
            }
        }
    }

    //请求网络 进行注册
    private void initRegister() {
        String url = URLConstant.BASE_URL + "user/regist.do";
        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody;
        if (TextUtils.isEmpty(yaoQing)) {
            formBody = new FormBody.Builder()
                    .add("name", this.phoneNumber)
                    .add("password", this.password)
                    .add("code", this.yanZhengMa)
                    .add("oneAddress", this.province)
                    .add("twoAddress", this.city)
                    .add("threeAddress", this.district)
                    .add("fourAddress", this.address)
                    .build();
        } else {
            formBody = new FormBody.Builder()
                    .add("name", this.phoneNumber)
                    .add("password", this.password)
                    .add("code", this.yanZhengMa)
                    .add("referrerName", yaoQing)
                    .add("oneAddress", this.province)
                    .add("twoAddress", this.city)
                    .add("threeAddress", this.district)
                    .add("fourAddress", this.address)
                    .build();
        }
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = null;
                try {
                    result = response.body().string();
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(3);
                }
                parseRegister(result);
            }
        });
    }

    //解析注册
    private void parseRegister(String result) {

        Gson gson = new Gson();
        RegisterBean bean = gson.fromJson(result, RegisterBean.class);

        if (bean != null) {

            switch (bean.getState()) {
                case 0:
                    mHandler.sendEmptyMessage(4);//提交失败
                    break;
                case 1:
                    mHandler.sendEmptyMessage(5);
                    break;
                case 2:
                    mHandler.sendEmptyMessage(6);
                    break;
                case 3:
                    mHandler.sendEmptyMessage(7);
                    break;
                case 4:
                    mHandler.sendEmptyMessage(8);
                    break;
            }
        }
    }

}




